<template>
  <div class="WorkingSchedule" v-loading="loading" element-loading-text="正在加载中">
    <!-- <div style="margin-bottom: 30px">{{ type | currentstep }}</div> -->
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="选择生产加工单/采购单" name="one">
        <div>
          <el-form ref="form" :model="form" label-position="top" class="myform" v-if="!Priceid">
            <div v-if="!Priceid">
              <el-form-item label="加工厂" class="myform-item">
                <el-select
                  v-model="form.supplier_id"
                  placeholder="请选择"
                  @change="onChange"
                  clearable
                >
                  <el-option
                    v-for="item in factoryList"
                    :key="item.supplier_id"
                    :label="item.factory_name"
                    :value="item.supplier_id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="年月" class="myform-item">
                <el-date-picker
                  v-model="form.date"
                  type="month"
                  placeholder="选择月"
                  value-format="yyyy-MM"
                  @change="onChange"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="品牌" class="myform-item">
                <el-select
                  v-model="form.brand_code"
                  placeholder="请选择"
                  @change="onChange"
                  clearable
                >
                  <el-option
                    v-for="item in brands"
                    :key="item.brand_code"
                    :label="item.brand_name"
                    :value="item.brand_code"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="选中金额" class="myform-item" v-if="oneData.purchasein_order_total">
                <el-input disabled v-model="oneData.purchasein_order_total"></el-input>
              </el-form-item>
              <el-form-item label="选中数量" class="myform-item" v-if="oneData.order_total">
                <el-input disabled v-model="oneData.order_total"></el-input>
              </el-form-item>
            </div>
          </el-form>
          <el-table
            :data="tableData"
            style="width: 100%"
            border
            ref="multipleTable"
            @selection-change="handleSelectionChange"
            :height="height"
          >
            <el-table-column type="selection" width="55" v-if="!steptype"></el-table-column>
            <el-table-column label="生产加工单" align="center" prop="so_id"></el-table-column>
            <el-table-column label="采购单号" align="center" prop="po_id"></el-table-column>
            <el-table-column label="款号" align="center" prop="type_no"></el-table-column>
            <el-table-column label="大货成衣成本加价总价(含税)" align="center" prop="contract_price"></el-table-column>
            <el-table-column label="实付成衣成本加价总价(含税)" align="center" prop="pay_price"></el-table-column>
            <el-table-column label="数量" align="center" prop="totalnum"></el-table-column>
            <el-table-column label="审核状态" align="center" prop="status">
              <template slot-scope="{ row }">
                <div
                  :style="{
                    color:
                      row.status == 2
                        ? '#67C23A'
                        : row.status == 3
                          ? 'red'
                          : '',
                  }"
                >
                  {{
                    row.status == 0
                      ? "未提交"
                      : row.status == 1
                        ? "已提交"
                        : row.status == 2
                          ? "已通过" : row.status == 3
                            ? "已拒绝" : row.status == 4
                              ? "已取消"
                              : ""
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="货款金额(含税)" align="center" prop="cost_amount"></el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane :disabled="!Priceid" label="选择工序加工费" name="work">
        <div>
          <el-table
            :data="tableData"
            style="width: 100%"
            border
            ref="multipleTable"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" v-if="!steptype"></el-table-column>
            <el-table-column label="id" align="center" prop="id"></el-table-column>
            <el-table-column label="创建人" align="center" prop="adduser"></el-table-column>
            <el-table-column label="工序加工单" align="center" prop="working_number"></el-table-column>
            <el-table-column label="合同号" align="center" prop="factory_contract_no"></el-table-column>
            <el-table-column label="款号" align="center" prop="type_no"></el-table-column>
            <el-table-column label="工厂" align="center" prop="factory_name"></el-table-column>
            <el-table-column label="单价" align="center" prop="price"></el-table-column>
            <el-table-column label="数量" align="center" prop="num"></el-table-column>
            <el-table-column label="金额" align="center" prop="amount"></el-table-column>
            <el-table-column label="交期" align="center" prop="delivery_date"></el-table-column>
            <el-table-column label="创建时间" align="center" prop="createtime"></el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane :disabled="!Priceid" label="选择预付款" name="advance">
        <div>
          <el-table
            :data="tableData"
            style="width: 100%"
            border
            ref="multipleTable"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" v-if="!steptype"></el-table-column>
            <el-table-column label="id" align="center" prop="id"></el-table-column>
            <el-table-column label="合同号" align="center" prop="factory_contract_no">
              <template slot-scope="{ row }">
                <el-button
                  type="text"
                  @click="onLook(row.factory_contract_no)"
                >{{ row.factory_contract_no }}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="申请时间" align="center" prop="createtime"></el-table-column>
            <el-table-column label="预付款" align="center" prop="amount"></el-table-column>
            <el-table-column label="付款时间" align="center" prop="pay_time"></el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane :disabled="!Priceid" label="选择额外费用" name="additional">
        <div>
          <el-table
            :data="tableData"
            style="width: 100%"
            border
            ref="multipleTable"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" v-if="!steptype"></el-table-column>
            <el-table-column label="id" align="center" prop="id"></el-table-column>
            <el-table-column label="合同号" align="center" prop="factory_contract_no"></el-table-column>
            <el-table-column label="款号" align="center" prop="type_no"></el-table-column>
            <el-table-column label="品名" align="center" prop="product_name"></el-table-column>
            <el-table-column label="用途" align="center" prop="purpose"></el-table-column>
            <el-table-column label="单价" align="center" prop="price"></el-table-column>
            <el-table-column label="数量" align="center" prop="num"></el-table-column>
            <el-table-column label="总价" align="center" prop="amount"></el-table-column>
            <el-table-column label="备注" align="center" prop="remarks"></el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane :disabled="!Priceid" label="选择违约金/赔偿金金额" name="fine">
        <div>
          <el-table
            :data="tableData"
            style="width: 100%"
            border
            ref="multipleTable"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" v-if="!steptype"></el-table-column>
            <el-table-column label="id" align="center" prop="id"></el-table-column>
            <el-table-column label="合同号" align="center" prop="factory_contract_no"></el-table-column>
            <el-table-column label="款号" align="center" prop="type_no"></el-table-column>
            <el-table-column label="违约金/赔偿金金额" align="center" prop="amount"></el-table-column>
            <el-table-column label="违约金/赔偿金原因" align="center" prop="reason"></el-table-column>
            <el-table-column label="违约金/赔偿金备注" align="center" prop="remarks"></el-table-column>
            <el-table-column label="违约金/赔偿金申请日期" align="center" prop="createtime"></el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-button type="primary" style="margin-top: 20px" v-if="steptype" @click="onAgain">重新选择</el-button>
    <div style="margin: 40px 0 20px">已完成对账信息</div>
    <el-table :data="tableDataReconciliation" style="width: 100%" border>
      <el-table-column label="货款金额" align="center" prop="purchasein_amount"></el-table-column>
      <el-table-column label="工序费用" align="center" prop="work_amount"></el-table-column>
      <el-table-column label="预付款" align="center" prop="advance_amount"></el-table-column>
      <el-table-column label="额外费用" align="center" prop="additional_amount"></el-table-column>
      <el-table-column label="违约金/赔偿金金额" align="center" prop="fine_amount"></el-table-column>
      <el-table-column label="总开票金额" align="center" prop="kaip_amount"></el-table-column>
      <el-table-column label="总应付金额" align="center" prop="pay_amount"></el-table-column>
    </el-table>
    <div class="step">
      <div class="step-button">
        <el-button
          type="primary"
          size="default"
          :disabled="!form.supplier_id || !form.date"
          @click="previousstep"
          v-if="activeName != 'one'"
        >上一步</el-button>
        <el-button
          type="primary"
          size="default"
          :disabled="
            activeName != 'one'
              ? false
              : activeName == 'one' && multipleSelection.length
                ? false
                : true
          "
          @click="stepOne"
        >{{ activeName == "fine" ? "保存" : "保存并进入下一步" }}</el-button>
      </div>
    </div>
    <div class="step">
      <div class="step-button">
        <el-button type="primary" size="default" :disabled="!Priceid" @click="stepComplete">确认对账单</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  postAdminPricingGetPurchaseinListCount_embroidery,
  postHomeCodeGetFactory,
  postAdminPricingAddReconciliation,
  postAdminPricingGetAdvanceAmountList,
  postAdminPricingNextStep,
  postAdminPricingGetAdditionalAmountList,
  postAdminPricingGetFineAmountList,
  postAdminPricingLookReconciliationOrder,
  postAdminPricingGetWorkingProcedure,
  postAdminPricingAddReconciliation_total_new,
  postAdminPricinggetPurchaseinBrand_code
} from "@/api";
import pagination from "@/components/pagination.vue";
export default {
  components: { pagination },
  filters: {
    currentstep(val) {
      return (
        ["选择工序加工费", "选择预付款", "选择额外费用", "选择违约金/赔偿金金额"][val] ||
        "选择生产加工单/采购单"
      );
    },
  },
  data() {
    return {
      loading: false,
      activeName: "one",
      type: 0,
      steptype: false, // 是否显示重新选择
      height: `${document.documentElement.clientHeight - 500}`,
      factoryList: [],
      brands:[],
      oneData: {
        order_total: 0,
        purchasein_order_total: 0
      },
      form: {
        supplier_id: "",
        date: "",
        brand_code:"",
        type: 0,
      },
      Priceid: "",
      tableData: [],
      multipleSelection: [],
      tableDataReconciliation: [
        {
          purchasein_amount: 0,
          advance_amount: 0,
          additional_amount: 0,
          fine_amount: 0,
          kaip_amount: 0,
          pay_amount: 0,
          work_amount: 0,
        },
      ],
      selectList: "",
    };
  },
  async activated() {
    this.postHomeCodeGetFactory();
    this.postAdminPricinggetPurchaseinBrand_code()
    let Priceid = this.$route.query.Priceid;
    if (Priceid) {
      this.activeName = "one"
      this.type = 0
      this.steptype = false // 是否显示重新选择
      this.form = {
        supplier_id: "",
        date: "",
        type:0
      }
      this.tableData = []
      this.multipleSelection = []
      this.tableDataReconciliation = [
        {
          purchasein_amount: 0,
          advance_amount: 0,
          additional_amount: 0,
          fine_amount: 0,
          kaip_amount: 0,
          pay_amount: 0,
          work_amount: 0,
        }
      ]
      this.selectList = ""
      this.Priceid = Priceid
      let { activeName } = this
      await this.postAdminPricingLookReconciliationOrder()
      await this.selStep(activeName)
    } else {
      if (this.$route.query.type) {
        this.activeName = "one"
        this.type = 0
        this.steptype = false // 是否显示重新选择
        this.form = {
          supplier_id: "",
          date: "",
          type: 0
        }
        this.Priceid = ""
        this.tableData = []
        this.multipleSelection = []
        this.tableDataReconciliation = [
          {
            purchasein_amount: 0,
            advance_amount: 0,
            additional_amount: 0,
            fine_amount: 0,
            kaip_amount: 0,
            pay_amount: 0,
            work_amount: 0,
          }
        ]
        this.selectList = ""
      }

    }
  },
  methods: {
    async postAdminPricinggetPurchaseinBrand_code(){
      let res = await postAdminPricinggetPurchaseinBrand_code()
      this.brands = res.data
    },
    async handleClick(e) {
      console.log("被选中时", e);
      this.activeName = e.name;
      this.type = e.index;
      await this.postAdminPricingLookReconciliationOrder();
      let { activeName } = this;
      this.selStep(activeName);
    },
    onLook(id) {
      this.$router.push({ name: "Contractdetail", query: { id } });
    },
    // 回货单详情
    async postAdminPricingLookReconciliationOrder() {
      this.loading = true;
      let obj = {
        id: this.Priceid,
      };
      await postAdminPricingLookReconciliationOrder(obj)
        .then((res) => {
          let data = res.data;
          this.form.date = data.recon_time;
          this.form.supplier_id = data.supplier_id;
          this.selectList = data;
          this.loading = false;
          this.tableDataReconciliation = [
            {
              purchasein_amount: data.purchasein_amount || 0,
              advance_amount: data.advance_amount || 0,
              additional_amount: data.additional_amount || 0,
              fine_amount: data.fine_amount || 0,
              kaip_amount: data.kaip_amount || 0,
              pay_amount: data.pay_amount || 0,
              work_amount: data.work_amount || 0,
            },
          ];
        })
        .catch((err) => {
          this.loading = false;
        });
    },

    // 重新选择
    onAgain() {
      let { form, activeName } = this;
      this.steptype = false;
      if (activeName == "one") {
        this.postAdminPricingGetPurchaseinListCount_embroidery();
      }
      if (activeName == "work") {
        this.postAdminPricingGetWorkingProcedure();
      }
      if (activeName == "advance") {
        this.postAdminPricingGetAdvanceAmountList();
      }
      if (activeName == "additional") {
        this.postAdminPricingGetAdditionalAmountList();
      }
      if (activeName == "fine") {
        this.postAdminPricingGetFineAmountList();
      }
    },
    async selStep(e) {
      let { selectList, form } = this;
      if (e == "one") {
        if (selectList.purchaseinlist.length) {
          this.steptype = true;
          this.tableData = selectList.purchaseinlist;
        } else {
          this.steptype = false;
          await this.postAdminPricingGetPurchaseinListCount_embroidery();
        }
      }

      if (e == "work") {
        if (selectList.worklist.length) {
          this.tableData = selectList.worklist;
          this.steptype = true;
        } else {
          this.steptype = false;
          await this.postAdminPricingGetWorkingProcedure();
        }
      }

      if (e == "advance") {
        if (selectList.advancelist.length) {
          this.tableData = selectList.advancelist;
          this.steptype = true;
        } else {
          this.steptype = false;
          await this.postAdminPricingGetAdvanceAmountList();
        }
      }

      if (e == "additional") {
        if (selectList.additionallist.length) {
          this.tableData = selectList.additionallist;
          this.steptype = true;
        } else {
          this.steptype = false;
          await this.postAdminPricingGetAdditionalAmountList();
        }
      }

      if (e == "fine") {
        if (selectList.finelist.length) {
          this.tableData = selectList.finelist;
          this.steptype = true;
        } else {
          this.steptype = false;
          await this.postAdminPricingGetFineAmountList();
        }
      }
    },
    // 上一步
    async previousstep() {
      let { type } = this;
      --type;
      this.type = type;
      this.activeName = ["one", "work", "advance", "additional", "fine"][type];
      let { activeName } = this;
      await this.postAdminPricingLookReconciliationOrder();
      this.selStep(activeName);
    },

    // 工序费用列表
    async postAdminPricingGetWorkingProcedure() {
      this.$refs.multipleTable.clearSelection();
      this.multipleSelection = [];
      this.loading = true;
      let form = JSON.parse(JSON.stringify(this.form))
      form.k_status = 0
      form.status = 1
      form.is_seconciliation= 1
      await postAdminPricingGetWorkingProcedure(form)
        .then((res) => {
          this.loading = false;
          console.log("工序费用列表", res);
          this.tableData = res.data;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 预付款列表
    async postAdminPricingGetAdvanceAmountList() {
      this.$refs.multipleTable.clearSelection();
      this.multipleSelection = [];
      this.loading = true;
      let form = JSON.parse(JSON.stringify(this.form))
      form.k_status = 1
      form.status = 1
      form.is_seconciliation= 1
      await postAdminPricingGetAdvanceAmountList(form)
        .then((res) => {
          this.loading = false;
          console.log("预付款列表", res);
          this.tableData = res.data;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 额外费列表
    async postAdminPricingGetAdditionalAmountList() {
      this.$refs.multipleTable.clearSelection();
      this.multipleSelection = [];
      this.loading = true;
      let form = JSON.parse(JSON.stringify(this.form))
      form.k_status = 0
      form.status = 1
      form.is_seconciliation= 1
      await postAdminPricingGetAdditionalAmountList(form)
        .then((res) => {
          this.loading = false;
          console.log("额外费列表", res);
          this.tableData = res.data;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 违约金/赔偿金列表
    async postAdminPricingGetFineAmountList() {
      this.$refs.multipleTable.clearSelection();
      this.multipleSelection = [];
      this.loading = true;
      let form = JSON.parse(JSON.stringify(this.form))
      form.k_status = 0
      form.status = 1
      form.is_seconciliation= 1
      await postAdminPricingGetFineAmountList(form)
        .then((res) => {
          this.loading = false;
          console.log("违约金/赔偿金列表", res);
          this.tableData = res.data;
        })
        .catch((err) => {
          this.loading = false;
        });
    },

    // 回货单统计列表
    async postAdminPricingGetPurchaseinListCount_embroidery() {
      this.loading = true;
      let form = JSON.parse(JSON.stringify(this.form))
      // form.k_status = 0
      postAdminPricingGetPurchaseinListCount_embroidery(form)
        .then((res) => {
          this.loading = false;
          console.log("回货单统计列表", res);
          this.tableData = res.data;
        })
        .catch((err) => {
          this.loading = false;
        });
    },

    // 改变时
    onChange() {
      let form = this.form;
      this.$refs.multipleTable.clearSelection();
      this.multipleSelection = [];
      if (form.supplier_id && form.date && form.brand_code) {
        this.postAdminPricingGetPurchaseinListCount_embroidery();
      }
    },
    // 加工厂列表
    postHomeCodeGetFactory() {
      let obj = {
        type:1,
        page: 1,
        size: 1000,
      };
      postHomeCodeGetFactory(obj).then((res) => {
        this.factoryList = res.data;
      });
    },
    handleSelectionChange(val) {
      this.loading = true
      this.multipleSelection = val;
      let { form, activeName } = this
      if (!val.length) {
        this.oneData = {
          order_total: 0,
          purchasein_order_total: 0
        }
      }
      if (activeName == "one" && val.length) {
        let arr = []
        val.forEach(e => {
          arr.push(e.id)
        })
        let obj = {
          supplier_id: form.supplier_id,
          date: form.date,
          type:0,
          brand_code:form.brand_code,
          ids: arr
        }
        postAdminPricingAddReconciliation_total_new(obj).then(res => {
          console.log("选中的数据---------->", res);
          this.oneData = res.data
          this.loading = false
        }).catch(err => {
          this.loading = false
        })
      } else {
        this.loading = false
      }
    },
    // 下一步
    async postAdminPricingNextStep() {
      let { Priceid, form, multipleSelection, type, activeName } = this;
      console.log("postAdminPricingNextStep", activeName);
      let obj = {
        step: activeName,
        ids: [],
        is_seconciliation: 1
      };
      if (Priceid) {
        obj.id = Priceid;
      }
      if (activeName == "one") {
        if (multipleSelection.length) {
          obj.date = form.date;
          obj.supplier_id = form.supplier_id;

          multipleSelection.forEach((e) => {
            if (e.ids != null) {
              obj.ids.push(e.id);
            }
          });
          obj.brand_code=form.brand_code
          delete obj.step;
          await postAdminPricingAddReconciliation(obj).then((res) => {
            let data = res.data;
            this.Priceid = data.id;
            this.type = Number(data.step);

            this.tableDataReconciliation = [
              {
                purchasein_amount: data.purchasein_amount || 0,
                advance_amount: data.advance_amount || 0,
                additional_amount: data.additional_amount || 0,
                fine_amount: data.fine_amount || 0,
                kaip_amount: data.kaip_amount || 0,
                pay_amount: data.pay_amount || 0,
              },
            ];
            this.$message.success("保存成功");
          }).catch((err) => {
            this.loading = false;
            --type
          });
        }
      } else {
        multipleSelection.forEach((e) => {
          obj.ids.push(e.id);
        });
        await postAdminPricingNextStep(obj).then((res) => {
          let data = res.data;
          this.tableDataReconciliation = [
            {
              purchasein_amount: data.purchasein_amount || 0,
              advance_amount: data.advance_amount || 0,
              additional_amount: data.additional_amount || 0,
              fine_amount: data.fine_amount || 0,
              kaip_amount: data.kaip_amount || 0,
              pay_amount: data.pay_amount || 0,
              work_amount: data.work_amount || 0,
            },
          ];
          this.$message.success("保存成功");
        }).catch((err) => {
          this.loading = false;
          --type
        });
      }
      ++type;
      this.type = type;
      if (activeName != "fine") {
        this.activeName = ["one", "work", "advance", "additional", "fine"][type];
      }

    },
    // 完成
    stepComplete() {
      let { Priceid } = this
      let obj = {
        id: Priceid,
        data_status: 1,
        is_seconciliation: 1
      }
      postAdminPricingNextStep(obj).then(res => {
        this.$message.success('完成')
        this.$router.go(-1)
      }).catch((err) => {
        this.loading = false;
      });
    },
    // 下一步
    async stepOne() {
      this.loading = true
      let activeName = this.activeName;
      switch (activeName) {
        case "one":
          await this.postAdminPricingNextStep();
          await this.postAdminPricingGetWorkingProcedure();
          this.loading = false
          break;
        case "work":
          await this.postAdminPricingNextStep();
          await this.postAdminPricingGetAdvanceAmountList();
          this.loading = false
          break;
        case "advance":
          await this.postAdminPricingNextStep();
          await this.postAdminPricingGetAdditionalAmountList();
          this.loading = false
          break;
        case "additional":
          await this.postAdminPricingNextStep();
          await this.postAdminPricingGetFineAmountList();
          this.loading = false
          break;
        case "fine":
          await this.postAdminPricingNextStep();
          this.loading = false
          break;
      }
    },
    // 搜索
    onSearch() {
      this.postAdminPricingGetPurchaseinListCount_embroidery();
    },
  },
};
</script>

<style lang="scss" scoped>
.step {
  height: 100px;
  &-button {
    padding-top: 40px;
    float: right;
  }
}
.myform {
  display: flex;
  justify-content: space-between;
  > div {
    display: flex;
  }
  &-item {
    margin-right: 10px;
  }
}
.WorkingSchedule {
  background: #ffff;
  padding: 20px;
  border-radius: 2px;
  @include boxShadow;
}
</style>
